#!/bin/bash
# Option Module Build Script
# This script builds only the option.ko module for USB serial devices

# Color functions
red=$(tput setaf 1)
reset=$(tput sgr0)

echo_error() {
    echo "${red}Error: $1${reset}" >&2
}

echo_info() {
    echo "$1"
}

# Default source directory
SOURCE_TARGET="/usr/src"
KERNEL_SRC="${SOURCE_TARGET}/kernel/kernel-jammy-src"

# Check for kernel source directory
if [ ! -d "$KERNEL_SRC" ]; then
    echo_error "内核源码未找到: $KERNEL_SRC"
    exit 1
fi

# Capture the original directory
ORIGINAL_DIR=$(pwd)

# Set up logging
LOGS_DIR="$ORIGINAL_DIR/logs"
mkdir -p "$LOGS_DIR"
LOG_FILE="$LOGS_DIR/option_module_build.log"

# Refresh sudo timestamp
sudo -v

# Change to kernel source directory
cd "$KERNEL_SRC" || {
    echo_error "无法切换到 $KERNEL_SRC"
    exit 1
}

# Determine number of jobs for parallel building
NUM_CPU=$(nproc)
JOBS=$((NUM_CPU > 1 ? NUM_CPU - 1 : 1))

# Build option module with logging
echo_info "在 $KERNEL_SRC 中编译option模块"
echo "编译option模块..." | tee -a "$LOG_FILE"

# 准备编译环境
time sudo make modules_prepare 2>&1 | tee -a "$LOG_FILE"

# 编译option模块
time sudo make -j$JOBS M=drivers/usb/serial CONFIG_USB_SERIAL_OPTION=m modules 2>&1 | tee -a "$LOG_FILE"
if [ ${PIPESTATUS[0]} -ne 0 ]; then
    echo "并行编译失败，尝试单线程编译..." | tee -a "$LOG_FILE"
    time sudo make M=drivers/usb/serial CONFIG_USB_SERIAL_OPTION=m modules 2>&1 | tee -a "$LOG_FILE"
    if [ ${PIPESTATUS[0]} -ne 0 ]; then
        echo_error "编译再次失败，请查看 $LOG_FILE 获取详情"
        exit 1
    fi
fi

# 检查option.ko是否存在
if [ ! -f "drivers/usb/serial/option.ko" ]; then
    echo_error "编译完成但未找到option.ko文件"
    exit 1
fi

echo_info "option模块编译成功"

# 询问是否安装模块
read -p "是否安装option模块? (y/n): " choice
if [ "$choice" = "y" ] || [ "$choice" = "Y" ]; then
    # 备份原有模块
    sudo cp /lib/modules/$(uname -r)/kernel/drivers/usb/serial/option.ko /lib/modules/$(uname -r)/kernel/drivers/usb/serial/option.ko.bak
    
    # 安装新模块
    echo "安装option模块..." | tee -a "$LOG_FILE"
    sudo cp drivers/usb/serial/option.ko /lib/modules/$(uname -r)/kernel/drivers/usb/serial/
    sudo depmod -a
    echo_info "模块安装成功，您可以使用以下命令加载新模块："
    echo "sudo rmmod option"
    echo "sudo modprobe option"
else
    echo_info "模块编译成功但未安装，您可以稍后手动安装："
    echo "sudo cp $KERNEL_SRC/drivers/usb/serial/option.ko /lib/modules/$(uname -r)/kernel/drivers/usb/serial/"
    echo "sudo depmod -a"
fi

# 最终日志文件通知
echo_info "日志保存在: $LOG_FILE"

exit 0
